import React, { useState } from 'react';
import {
  Card,
  Typography,
  Button,
  Input,
  Table,
  Tag,
  Space,
  Statistic,
  Row,
  Col,
  Tooltip,
  Alert,
  Modal,
  QRCode,
  message,
  Tabs,
  List,
  Progress
} from 'antd';
import {
  ShareAltOutlined,
  CopyOutlined,
  TeamOutlined,
  TrophyOutlined,
  UserOutlined,
  GiftOutlined,
  CalendarOutlined,
  QrcodeOutlined,
  FacebookOutlined,
  TwitterOutlined,
  WhatsappOutlined,
  TelegramOutlined
} from '@ant-design/icons';

import { useAuth } from '../contexts/AuthContext';
import { useQuery } from 'react-query';

const { Title, Text } = Typography;
const { TabPane } = Tabs;

const Referrals = () => {
  const [qrModalVisible, setQrModalVisible] = useState(false);
  const [shareModalVisible, setShareModalVisible] = useState(false);

  const { apiCall } = useAuth();

  // Fetch referral information
  const { data: referralInfo } = useQuery(
    'referralInfo',
    () => apiCall('GET', '/referrals/info'),
    { refetchInterval: 30000 }
  );

  // Fetch referral earnings
  const { data: earningsData } = useQuery(
    'referralEarnings',
    () => apiCall('GET', '/referrals/earnings'),
    { refetchInterval: 30000 }
  );

  const copyToClipboard = (text, type) => {
    navigator.clipboard.writeText(text);
    message.success(`${type} copied to clipboard!`);
  };

  const shareOnSocialMedia = (platform, referralLink) => {
    const text = `Join me on God Token Staking and earn daily rewards! Use my referral link: ${referralLink}`;
    const encodedText = encodeURIComponent(text);
    const encodedUrl = encodeURIComponent(referralLink);

    let url = '';
    switch (platform) {
      case 'facebook':
        url = `https://www.facebook.com/sharer/sharer.php?u=${encodedUrl}`;
        break;
      case 'twitter':
        url = `https://twitter.com/intent/tweet?text=${encodedText}`;
        break;
      case 'whatsapp':
        url = `https://wa.me/?text=${encodedText}`;
        break;
      case 'telegram':
        url = `https://t.me/share/url?url=${encodedUrl}&text=${encodedText}`;
        break;
      default:
        return;
    }

    window.open(url, '_blank', 'width=600,height=400');
  };

  const formatAddress = (address) => {
    if (!address) return '';
    return `${address.slice(0, 6)}...${address.slice(-4)}`;
  };

  const formatNumber = (num, decimals = 2) => {
    if (!num) return '0';
    return parseFloat(num).toFixed(decimals);
  };

  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleDateString();
  };

  const recentReferralsColumns = [
    {
      title: 'Referral',
      dataIndex: 'wallet_address',
      key: 'address',
      render: (address) => (
        <Space>
          <UserOutlined />
          <Text code>{formatAddress(address)}</Text>
        </Space>
      )
    },
    {
      title: 'Joined Date',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (date) => formatDate(date)
    },
    {
      title: 'Total Rewards',
      dataIndex: 'total_rewards',
      key: 'rewards',
      render: (rewards) => (
        <Text strong className="text-green-600">
          {formatNumber(rewards)} GOD
        </Text>
      )
    },
    {
      title: 'Status',
      key: 'status',
      render: (_, record) => (
        <Tag color="green">Active</Tag>
      )
    }
  ];

  const rewardHistoryColumns = [
    {
      title: 'Date',
      dataIndex: 'created_at',
      key: 'date',
      render: (date) => (
        <Space>
          <CalendarOutlined />
          {formatDate(date)}
        </Space>
      )
    },
    {
      title: 'Type',
      dataIndex: 'reward_type',
      key: 'type',
      render: (type) => {
        const config = {
          'deposit_bonus': { color: 'blue', text: 'Deposit Bonus' },
          'staking_bonus': { color: 'green', text: 'Staking Bonus' }
        };
        const typeConfig = config[type] || { color: 'default', text: type };
        return <Tag color={typeConfig.color}>{typeConfig.text}</Tag>;
      }
    },
    {
      title: 'Amount',
      dataIndex: 'reward_amount',
      key: 'amount',
      render: (amount) => (
        <Text strong className="text-green-600">
          +{formatNumber(amount)} GOD
        </Text>
      )
    },
    {
      title: 'From User',
      dataIndex: 'referred_user_address',
      key: 'from_user',
      render: (address) => (
        <Text code>{formatAddress(address)}</Text>
      )
    }
  ];

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="mb-8">
          <Title level={2} className="text-gray-900 mb-2">Referral Program</Title>
          <Text className="text-gray-600">Earn 10% rewards from your direct referrals</Text>
        </div>

        {/* Referral Info Alert */}
        <Alert
          message="How It Works"
          description={
            <div>
              <p>• Share your referral link with friends and family</p>
              <p>• Earn 10% rewards from their deposits</p>
              <p>• Track your referrals and earnings in real-time</p>
              <p>• No limit on the number of referrals</p>
            </div>
          }
          type="info"
          showIcon
          className="mb-8"
        />

        {/* Stats Cards */}
        <Row gutter={[16, 16]} className="mb-8">
          <Col xs={24} sm={8}>
            <Card>
              <Statistic
                title="Total Referrals"
                value={referralInfo?.stats?.total_referrals || 0}
                prefix={<TeamOutlined />}
                suffix="users"
              />
            </Card>
          </Col>
          <Col xs={24} sm={8}>
            <Card>
              <Statistic
                title="Total Rewards Earned"
                value={formatNumber(referralInfo?.stats?.total_referral_rewards)}
                prefix={<TrophyOutlined />}
                suffix="GOD"
                precision={2}
              />
            </Card>
          </Col>
          <Col xs={24} sm={8}>
            <Card>
              <Statistic
                title="This Month"
                value={referralInfo?.stats?.referrals_this_month || 0}
                prefix={<CalendarOutlined />}
                suffix="referrals"
              />
            </Card>
          </Col>
        </Row>

        {/* Referral Link Section */}
        <Card title="Your Referral Link" className="mb-8">
          <Space direction="vertical" className="w-full">
            <div className="bg-blue-50 p-4 rounded-lg">
              <Input
                value={referralInfo?.referralLink || ''}
                readOnly
                size="large"
                addonBefore={
                  <Space>
                    <ShareAltOutlined />
                    <Text strong>Referral Link:</Text>
                  </Space>
                }
                addonAfter={
                  <Button
                    type="primary"
                    icon={<CopyOutlined />}
                    onClick={() => copyToClipboard(referralInfo?.referralLink, 'Referral link')}
                  >
                    Copy
                  </Button>
                }
              />
            </div>

            <div className="flex flex-wrap gap-2">
              <Button
                icon={<QrcodeOutlined />}
                onClick={() => setQrModalVisible(true)}
              >
                Show QR Code
              </Button>
              <Button
                icon={<FacebookOutlined />}
                onClick={() => shareOnSocialMedia('facebook', referralInfo?.referralLink)}
              >
                Facebook
              </Button>
              <Button
                icon={<TwitterOutlined />}
                onClick={() => shareOnSocialMedia('twitter', referralInfo?.referralLink)}
              >
                Twitter
              </Button>
              <Button
                icon={<WhatsappOutlined />}
                onClick={() => shareOnSocialMedia('whatsapp', referralInfo?.referralLink)}
              >
                WhatsApp
              </Button>
              <Button
                icon={<TelegramOutlined />}
                onClick={() => shareOnSocialMedia('telegram', referralInfo?.referralLink)}
              >
                Telegram
              </Button>
            </div>

            <Alert
              message="Pro Tip"
              description="Share your referral link on social media and with friends to maximize your earnings!"
              type="success"
              showIcon
            />
          </Space>
        </Card>

        {/* Referral Details Tabs */}
        <Tabs defaultActiveKey="referrals">
          <TabPane
            tab={`Recent Referrals (${referralInfo?.recentReferrals?.length || 0})`}
            key="referrals"
          >
            <Card>
              {referralInfo?.recentReferrals?.length > 0 ? (
                <Table
                  columns={recentReferralsColumns}
                  dataSource={referralInfo.recentReferrals}
                  pagination={{
                    pageSize: 10,
                    showSizeChanger: true,
                    showQuickJumper: true
                  }}
                  rowKey="id"
                />
              ) : (
                <div className="text-center py-8">
                  <TeamOutlined className="text-4xl text-gray-300 mb-4" />
                  <Text type="secondary">No referrals yet</Text>
                  <div className="mt-4">
                    <Text type="secondary">Start sharing your referral link to earn rewards!</Text>
                  </div>
                </div>
              )}
            </Card>
          </TabPane>

          <TabPane
            tab={`Reward History (${referralInfo?.rewardHistory?.length || 0})`}
            key="rewards"
          >
            <Card>
              {referralInfo?.rewardHistory?.length > 0 ? (
                <Table
                  columns={rewardHistoryColumns}
                  dataSource={referralInfo.rewardHistory}
                  pagination={{
                    pageSize: 10,
                    showSizeChanger: true,
                    showQuickJumper: true
                  }}
                  rowKey="id"
                />
              ) : (
                <div className="text-center py-8">
                  <TrophyOutlined className="text-4xl text-gray-300 mb-4" />
                  <Text type="secondary">No rewards yet</Text>
                </div>
              )}
            </Card>
          </TabPane>

          <TabPane tab="Earnings Overview" key="earnings">
            <Card>
              {earningsData?.earnings?.length > 0 ? (
                <div className="space-y-6">
                  {earningsData.earnings.map((earning, index) => (
                    <div key={index} className="border rounded-lg p-4">
                      <div className="flex justify-between items-start mb-2">
                        <Title level={5} className="mb-0">
                          {earning.reward_type === 'deposit_bonus' ? 'Deposit Bonuses' : 'Staking Bonuses'}
                        </Title>
                        <Tag color="blue">
                          {earning.reward_count} rewards
                        </Tag>
                      </div>
                      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div>
                          <Text type="secondary">Total Amount:</Text>
                          <div>
                            <Text strong className="text-green-600">
                              {formatNumber(earning.total_rewards)} GOD
                            </Text>
                          </div>
                        </div>
                        <div>
                          <Text type="secondary">Average Reward:</Text>
                          <div>
                            <Text>{formatNumber(earning.average_reward)} GOD</Text>
                          </div>
                        </div>
                        <div>
                          <Text type="secondary">Period:</Text>
                          <div>
                            <Text>{earningsData.period}</Text>
                          </div>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="text-center py-8">
                  <GiftOutlined className="text-4xl text-gray-300 mb-4" />
                  <Text type="secondary">No earnings data available</Text>
                </div>
              )}
            </Card>
          </TabPane>
        </Tabs>

        {/* QR Code Modal */}
        <Modal
          title="Referral QR Code"
          open={qrModalVisible}
          onCancel={() => setQrModalVisible(false)}
          footer={[
            <Button key="close" onClick={() => setQrModalVisible(false)}>
              Close
            </Button>
          ]}
        >
          <div className="text-center">
            <div className="mb-4">
              <QRCode value={referralInfo?.referralLink || ''} size={256} />
            </div>
            <Text>Scan this QR code to join with your referral link</Text>
            <div className="mt-4">
              <Button
                type="primary"
                icon={<CopyOutlined />}
                onClick={() => copyToClipboard(referralInfo?.referralLink, 'Referral link')}
              >
                Copy Link
              </Button>
            </div>
          </div>
        </Modal>
      </div>
    </div>
  );
};

export default Referrals;